package cn.xz.tipsum


import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import cn.xz.tipsum.activity.DeviceActivity
import cn.xz.tipsum.activity.ErrorActivity
import cn.xz.tipsum.activity.SettingActivity
import cn.xz.tipsum.activity.TwoActivity
import cn.xz.tipsum.adapter.MyListAdapter
import cn.xz.tipsum.bean.*
import cn.xz.tipsum.databinding.ActivityMainBinding
import cn.xz.tipsum.dialog.ErrorDialog
import cn.xz.tipsum.dialog.LoseAppDialog
import cn.xz.tipsum.dialog.SelectDialog
import cn.xz.tipsum.utils.*
import org.greenrobot.eventbus.Subscribe
import java.math.BigDecimal
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : AppCompatActivity() {

    private var mDataBind: ActivityMainBinding?  = null

    private var mAdapter: MyListAdapter? = null

    private var handler: Handler? = null

    //过期时间
    private val mT = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //设置屏幕常亮
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        EventBusUtils.register(this)
        mDataBind = DataBindingUtil.setContentView(this, R.layout.activity_main)

        //判断是否是同一个设备，如果不是禁止使用
        if (MD5Utils.getMD5(AppHelper.getUUID()) != "7b33e559496f8682ab2d060cfa3571f2"){
            Log.e("8806", "initData:当前设备编号--- " + MD5Utils.getMD5(AppHelper.getUUID()))
            LoseAppDialog.newInstance(object : LoseAppDialog.OnClickListener{
                override fun onF() {
                    finishAffinity()
                }

            }).show(this.supportFragmentManager,"LoseAppDialog")
        }else{
            getTZ()
            initData()
            initTime()
            initEvent()
            initRv()
        }
    }

    private fun initData(){
        var mD = ContextCompat.getDrawable(this,R.mipmap.icon_close)
        var mO = View.GONE
        var mC = View.VISIBLE
        if (SessionUtils.getBoolean(SessionUtils.OPEN_EYE,true)){
            mO = View.VISIBLE
            mC = View.GONE
            mD = ContextCompat.getDrawable(this,R.mipmap.icon_open)
        }
        mDataBind?.tvTxtOpen?.visibility = mO
        mDataBind?.tvTxtClose?.visibility = mC
        mDataBind?.ivEyes?.setImageDrawable(mD)
    }

    private fun initRv(){
        val ms = LinearLayoutManager(this)
        mAdapter = MyListAdapter()
        mDataBind?.rvList?.layoutManager = ms
        mDataBind?.rvList?.adapter = mAdapter
        //RecyclerView闪烁问题
        (mDataBind?.rvList?.itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
    }

    private fun initTime(){
        //开启定时器获取时间
        handler = Handler()
        handler?.post(movieR)
    }

    private var movieR: Runnable = object : Runnable {
        override fun run() {
            mDataBind?.tvTime?.post {
                val formatter = SimpleDateFormat("HH:mm")
                val curDate = Date(System.currentTimeMillis())
                mDataBind?.tvTime?.text = formatter.format(curDate)
                //周几
                val week: Int = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
                setWeek(week)
                //几号
                val day: Int = Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
                mDataBind?.tvDay?.text = "$day 号"
                //判断是否当天
                setDataS()
            }
            handler?.postDelayed(this, 1000)
        }
    }

    private fun initEvent(){
       //睁眼-闭眼
       mDataBind?.llcO?.setOnClickListener {
           setOpen()
           var mD = ContextCompat.getDrawable(this,R.mipmap.icon_close)
           var mO = View.GONE
           var mC = View.VISIBLE
           if (SessionUtils.getBoolean(SessionUtils.OPEN_EYE,true)){
               mO = View.VISIBLE
               mC = View.GONE
               mD = ContextCompat.getDrawable(this,R.mipmap.icon_open)
           }
           mDataBind?.tvTxtOpen?.visibility = mO
           mDataBind?.tvTxtClose?.visibility = mC
           mDataBind?.ivEyes?.setImageDrawable(mD)
       }
        //权限弹窗
        mDataBind?.tvWeek?.setOnClickListener {
            //addData(MyBean("V","99.99","23:59:00"))
            //addData(MyBean("Z","99.99","23:59:00"))
            //SelectDialog.newInstance().show(this.supportFragmentManager,"SelectDialog4214")
            startActivity(Intent(this, ErrorActivity::class.java))
            //ServiceUtils.isServiceRunning("MyNotificationListenerService",this)
            /*MyNotificationListenerService.processOnReceive("com.eg.android.AlipayGphone",
                "店员通",
                "支付宝成功收款93.00元，点击查看",
                "18:52"
            )*/
        }
        //第二模式
        mDataBind?.tvTime?.setOnClickListener {
            if (NEW_OPEN){
                startActivity(Intent(this, TwoActivity::class.java))
            }
        }
        //设备信息
        mDataBind?.tvDay?.setOnClickListener {
            startActivity(Intent(this, DeviceActivity::class.java))
        }
        //设置界面
        mDataBind?.tvSetting?.setOnClickListener {
            if (NEW_OPEN){
                startActivity(Intent(this, SettingActivity::class.java))
            }
        }
        //是否显示金额
        mDataBind?.tvMode?.setOnClickListener {
            if (mDataBind?.llcLeft?.isVisible == true){
                mDataBind?.llcLeft?.visibility = View.GONE
            }else{
                mDataBind?.llcLeft?.visibility = View.VISIBLE
            }
        }
        /*mDataBind?.tvTxtOpen?.setOnClickListener {
            val formatter = SimpleDateFormat("HH:mm")
            val curDate = Date(System.currentTimeMillis())
            val math = (Math.random() * 20).toInt() + 1
            addData(MyBean("Z",math.toString(),formatter.format(curDate)))
        }
        mDataBind?.tvTxtClose?.setOnClickListener {
            val formatter = SimpleDateFormat("HH:mm")
            val curDate = Date(System.currentTimeMillis())
            val math = (Math.random() * 20).toInt() + 1
            addData(MyBean("V",math.toString(),formatter.format(curDate)))
        }*/
    }

    //添加数据
    private fun addData(mBean: MyBean){
        if (mAdapter != null){
            try {
                mAdapter!!.addData(mBean)
                putData(mBean)
                val mList = mAdapter!!.data as ArrayList<MyBean>
                setM(mList)
            }catch (e: java.lang.Exception){
                e.printStackTrace()
            }
        }
    }

    //设置睁眼闭眼
    private fun setOpen(){
        var mInput = true
        if (SessionUtils.getBoolean(SessionUtils.OPEN_EYE,true)){
            mInput = false
        }
        SessionUtils.commitBoolean(SessionUtils.OPEN_EYE,mInput)
    }


    //打开使用通知框权限
    private fun getTZ(){
        // 判断是否开启监听通知权限
        if (NotificationManagerCompat.getEnabledListenerPackages(this).contains(packageName)) {
            /*val serviceIntent =  Intent(this, MyNotificationListenerService::class.java)
            //防止重复创建
            if (ServiceUtils.isServiceRunning("MyNotificationListenerService",this)){
                Log.e("收到","已存在不创建");
            }else{
                startService(serviceIntent)
            }*/
            ServiceUtils.toggleNotificationListenerService(this)
        }else {
            // 去开启 监听通知权限
            startActivity( Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"));
        }
    }

    @Subscribe
    fun onSubscriberEvent(message: EventBusMessage) {
        when(message.messageTag) {
            GET_MSG -> { //刷新评论
                mDataBind?.rvList?.post {
                    try {
                        val mB = message.messageBody as MyBean
                        addData(mB)
                    }catch (e: Exception){
                        e.printStackTrace()
                    }
                }
            }
            ERROR_CODE->{
                mDataBind?.tvTime?.post {
                    try {
                        val mB = message.messageBody as String
                        ErrorDialog.newInstance(mB).show(this.supportFragmentManager,"ErrorDialog")
                    }catch (e: Exception){
                        e.printStackTrace()
                    }
                }
            }
        }
    }

    //同步存储数据
    private fun putData(mBean: MyBean){
        val mInputList = SessionUtils.getDataList(
            SessionUtils.INPUT_DATA,
            MyBean::class.java) as ArrayList<MyBean>
        mInputList.add(mBean)
        SessionUtils.commitDataList(SessionUtils.INPUT_DATA,mInputList)
    }

    //计算多少钱
    private fun setM(mList: ArrayList<MyBean>){
        mDataBind?.rvList?.postDelayed({
            //计算总金额
            var mAll = 0.0
            mList.forEach {
                val bd1 = BigDecimal(mAll.toString())
                val bd2 = BigDecimal(it.value.toString());
                mAll = bd1.add(bd2).toDouble()
            }
            var mS = 50f
            if (mAll > 1000){
                mS  = 30f
            }
            mDataBind?.tvTxtOpen?.textSize = mS
            mDataBind?.tvTxtClose?.textSize = mS
            mDataBind?.tvTxtOpen?.text = "${mAll}元"
            //列表滑到最底
            mDataBind?.rvList?.smoothScrollToPosition(mList.size)
        },100)
    }

    override fun onResume() {
        super.onResume()
        //判断当前存储数据是否当天
        val formatter = SimpleDateFormat("yyyyMMdd")
        val curDate = Date(System.currentTimeMillis())
        val nowData = formatter.format(curDate)
        //存储的日期
        val saveData = SessionUtils.getString(SessionUtils.INPUT_TIME,"")
        var mInputList: ArrayList<MyBean> = arrayListOf()
        if (nowData == saveData){
            //同一天读数据显示
            mInputList = SessionUtils.getDataList(
                SessionUtils.INPUT_DATA,
                MyBean::class.java) as ArrayList<MyBean>
        }else{
            //不同一天清数据
            SessionUtils.commitString(SessionUtils.INPUT_TIME,nowData)
            val mList: List<MyBean> = arrayListOf()
            SessionUtils.commitDataList(SessionUtils.INPUT_DATA,mList)
        }
        if (mAdapter != null){
            mAdapter!!.setList(mInputList)
            //计算多少钱
            setM(mInputList)
        }

        //设置到期时间
        //2024-2-26 =  1708917495
        if (mT != 0L){
            if (System.currentTimeMillis() > mT){
                Toast.makeText(this,"应用已过期，请联系管理员",Toast.LENGTH_LONG).show()
                finish()
            }
        }
    }

    private fun setDataS(){
        //判断当前存储数据是否当天
        val formatter = SimpleDateFormat("yyyyMMdd")
        val curDate = Date(System.currentTimeMillis())
        val nowData = formatter.format(curDate)
        //存储的日期
        val saveData = SessionUtils.getString(SessionUtils.INPUT_TIME,"")
        val mInputList: ArrayList<MyBean> = arrayListOf()
        if (nowData != saveData){
            //不同天,存储新日期
            SessionUtils.commitString(SessionUtils.INPUT_TIME,nowData)
            //清空存储数据
            val mList: List<MyBean> = arrayListOf()
            SessionUtils.commitDataList(SessionUtils.INPUT_DATA,mList)
            //清空列表
            if (mAdapter != null){
                mAdapter!!.setList(mInputList)
                //计算多少钱
                setM(mInputList)
            }
        }
    }


    //周几
    private fun setWeek(week: Int){
        var mStr = ""
        when(week - 1){
            0->{
                mStr = "星期天"
            }
            1->{
                mStr = "星期一"
            }
            2->{
                mStr = "星期二"
            }
            3->{
                mStr = "星期三"
            }
            4->{
                mStr = "星期四"
            }
            5->{
                mStr = "星期五"
            }
            6->{
                mStr = "星期六"
            }
        }
        if (mDataBind?.tvWeek?.text != mStr){
            mDataBind?.tvWeek?.text = mStr
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        EventBusUtils.unRegister(this)
        if (handler != null){
            handler?.removeCallbacks(movieR)
            handler = null
        }
    }
}